package cn.yudao.ymcc.mq.comsumer;


import cn.yudao.ymcc.domain.MessageEmail;
import cn.yudao.ymcc.domain.MessageSms;
import cn.yudao.ymcc.domain.User;
import cn.yudao.ymcc.dto.OnLineSmsDto;
import cn.yudao.ymcc.service.IMessageEmailService;
import cn.yudao.ymcc.service.IMessageSmsService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@RocketMQMessageListener(consumerGroup="service-common-consumer-email",
        topic="topic-online",
        selectorExpression="rag-email",
        messageModel = MessageModel.CLUSTERING) // 默认是集群 1个消息被一个消费者消费 MessageModel.BROADCASTING 广播 1个消息被所有的消费者消费
public class OnLineEmailConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageEmailService messageEmailService;


    @Override
    public void onMessage(MessageExt message) {
        // 拿到对象
        byte[] body = message.getBody();
        OnLineSmsDto onLineSmsDto = JSONObject.parseObject(body, OnLineSmsDto.class);
        // 添加到发送短信日志
        ArrayList<MessageEmail> messageEmail1 = new ArrayList<>();
        List<User> users = onLineSmsDto.getUsers();
        users.stream().map(user -> {
            MessageEmail messageEmail = new MessageEmail();
            messageEmail.setEmail(user.getEmail());
            messageEmail.setUserId(user.getId());
            messageEmail.setTitle("课程发布");
            messageEmail.setSendTime(new Date());
            messageEmail.setContent("亲爱的用户您好，最新课程 <a href='javaWEB班j'> javaWEB班j </a> 发布啦，点击课程了解详情");
            messageEmail1.add(messageEmail);
            // 调用发送邮件
            System.out.println("亲爱的用户您好，最新课程 <a href='javaWEB班j'> javaWEB班j </a> 发布啦，点击课程了解详情" + user.getEmail());
            return messageEmail;
        }).count();
        // 批量新增
        messageEmailService.insertBatch(messageEmail1);

    }

}
